//
//  ZCMainVC.m
//  zctx
//
//  Created by ZhengDarren on 15/9/28.
//  Copyright © 2015年 sanliang. All rights reserved.
//
#import "ZCLoginVC.h"
#import "ZCMainVC.h"
#import "Reachability.h"

#import "ZCSeeResultVC.h"
#import "ZCProjectdetailsVC.h"
#import "ZCRaiseVC.h"
#import "ZCSamplingVC.h"
#import "ZCInvolvedVC.h"
#import "DZWebViewController.h"

#import "DiscountCellH.h"
#import "ZCmainCell.h"
#import "ZCMainModel.h"
#import "AdView.h"

#import "ZCMeAuditDetailsVC.h"  //审核中
#import "ZCSamplingDetailVC.h"  //抽样中
#import "ZCInvolvedDetailsVC.h"  //众筹中
//#import "ZCProjectdetailsVC.h"  //结果

#import "UIsharePopoverListView.h"

@interface ZCMainVC ()<UITableViewDataSource,UITableViewDelegate,DiscountDelegate,UIsharePopoverListViewDelegate>
{
    NSMutableArray *mainArray;
    NSMutableArray *dataArray;
    NSMutableArray *adArray;
    AdView *adView;
    BOOL isconn;
}
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic, strong) Reachability *conn;
@end

@implementation ZCMainVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkState) name:kReachabilityChangedNotification object:nil];
    self.conn = [Reachability reachabilityForInternetConnection];
    [self.conn startNotifier];
    
    mainArray = [NSMutableArray array];
    dataArray = [NSMutableArray array];
    adArray = [NSMutableArray array];
    
    if (!UserModel.mid) {
        [UserModel setMid:@"0"];
        [UserModel setPassword:@"0"];
    }
    
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //
        [self initData];//初始化数据
        [self requestAds];//广告
    });
    [self initnavegation];//初始化导航栏内容
    
    
    [self requestMaindata];//请求首页数据
    
    [self initTableView]; //初始化UITableView
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCmainCell" bundle:nil] forCellReuseIdentifier:@"maincell"];
    
    
    [NetworkManager requestGetVerifyCodeWithAction:@"login" mobile:@"13800138000" success:^(NSDictionary *dictResponse) {
        
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark 导航栏
-(void)initnavegation{
    UIImageView *title_naImgaeView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 95, 20)];
    [title_naImgaeView setImage:[UIImage imageNamed:@"navigation_logo.png"]];
    self.navigationItem.titleView = title_naImgaeView;
    
    UIButton * rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 24, 22);
    [rightButton setImage:[UIImage imageNamed:@"main_share"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(shareButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_rightNavBar = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = barButtonItem_rightNavBar;
}

#pragma mark 初始化数据
-(void)initData{
    
    NSString *paththree = [[NSBundle mainBundle]pathForResource:@"ZCMain" ofType:@"plist"
                           ];
    mainArray = [[NSMutableArray alloc]initWithContentsOfFile:paththree];
}

#pragma mark 请求广告
-(void)requestAds{
    
    [NetworkManager requestIndexadlistsWithsuccess:^(NSDictionary *dictResponse) {
        
        adArray = (NSMutableArray *)[dictResponse objectForKey:@"content"];
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark 请求首页数据
-(void)requestMaindata{
    
    NSLog(@"userModel.mid = %@ , userModel.password = %@",UserModel.mid,UserModel.password);
    [NetworkManager requestFoundingGetLatestWithMid:UserModel.mid password:UserModel.password success:^(NSDictionary *dictResponse) {
        dataArray = (NSMutableArray *)[dictResponse objectForKey:@"content"];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}

-(void)initTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.sectionFooterHeight = 0.0001;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, -20,0));
    }];
}

#pragma mark UITableViewDataSource,UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    }else{
        return dataArray.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        static NSString *cellIndentifier = @"discountcell";
        DiscountCellH *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil) {
            cell = [[DiscountCellH alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        }
        cell.delegate = self;
        [cell setDiscountArray:mainArray];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        static NSString *caellid =@"maincell";
        ZCmainCell *cell = [tableView dequeueReusableCellWithIdentifier:caellid];
        if (cell == nil) {
            cell = [[ZCmainCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:caellid];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *dict = (NSDictionary *)dataArray[indexPath.row];
        ZCMainModel *moel =[ZCMainModel modelObjectWithDictionary:dict];
        cell.mainModel = moel;
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return 120;
    }else
    {
        return 90;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return ADViewHEIGHT;
    }else{
        return 45;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
//        NSString *mid =[NSString stringWithFormat:@"%@",[dataArray[indexPath.row] objectForKey:@"id"]];
        
        NSDictionary *dict = (NSDictionary *)dataArray[indexPath.row];
        ZCMainModel *moel =[ZCMainModel modelObjectWithDictionary:dict];
        ZCProjectdetailsVC *detailVC = [[ZCProjectdetailsVC alloc]init];
        detailVC.pid = moel.contentIdentifier;
        detailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==0) {
        NSMutableArray *imageURLs = [NSMutableArray array];
        for (NSDictionary *imageDic in adArray) {
            NSString *urlstr = [NSString stringWithFormat:@"%@%@",[NetworkManager strURLBasic],[imageDic objectForKey:@"img"]];
            [imageURLs addObject:urlstr];
        }        
        adView = [AdView adScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ADViewHEIGHT)  \
                                  imageLinkURL:imageURLs\
                           placeHoderImageName:@"placeHoder.jpg" \
                          pageControlShowStyle:UIPageControlShowStyleLeft];
        //    是否需要支持定时循环滚动，默认为YES
        //    adView.isNeedCycleRoll = YES;
        //    [adView setAdTitleArray:titles withShowStyle:AdTitleShowStyleRight];
        //    设置图片滚动时间,默认3s
        //    adView.adMoveTime = 2.0;
        
        __block ZCMainVC *weakSelf = self;
        //图片被点击后回调的方法
        adView.callBack = ^(NSInteger index,NSString * imageURL)
        {
            NSLog(@"被点中图片的索引:%ld---地址:%@",(long)index,imageURL);
            
            NSDictionary *model =(NSDictionary *)weakSelf->adArray[index];
            
            NSLog(@"model =%@",model);
            NSString *type = [NSString stringWithFormat:@"%@",[model objectForKey:@"type"]];
            NSString *state = [NSString stringWithFormat:@"%@",[model objectForKey:@"fd_state"]];
            NSString *fdid = [NSString stringWithFormat:@"%@",[model objectForKey:@"fdid"]];
            if ([type isEqualToString:@"0"]) {
                
                if ([state isEqualToString:@"0"])
                { // 0 审核中 1众筹中 2 抽样中 3完成 4 异常
                    
                    ZCMeAuditDetailsVC *vc = [[ZCMeAuditDetailsVC alloc]init];
                    vc.pid =fdid;
                    vc.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }else if ([state isEqualToString:@"1"]){
                    ZCInvolvedDetailsVC *vc = [[ZCInvolvedDetailsVC alloc]init];
                    vc.pid =fdid;
                    vc.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }else if ([state isEqualToString:@"2"]){
                    ZCSamplingDetailVC *vc = [[ZCSamplingDetailVC alloc]init];
                    vc.pid =fdid;
                    vc.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }else if ([state isEqualToString:@"3"]){
                    ZCProjectdetailsVC *vc = [[ZCProjectdetailsVC alloc]init];
                    vc.pid =fdid;
                    vc.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
                
            }else{
                NSString *url = [NSString stringWithFormat:@"%@",[model objectForKey:@"url"]];
                NSString *title = [NSString stringWithFormat:@"%@",[model objectForKey:@"title"]];
                if (url.length > 0) {
                    DZWebViewController *vc = [[DZWebViewController alloc] init];
                    vc.strURL = url;
                    vc.title = title;
                    vc.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
            }
        };
        return adView;

    }else{
        UIView * headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45)];
        headView.backgroundColor = [UIColor whiteColor];
        UIView *bgheadView = [UIView new];
        [headView addSubview:bgheadView];
        bgheadView.backgroundColor = [UIColor colorWithHexString:@"#ebeded"];
        [bgheadView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(headView.top).with.offset(0);
            make.left.equalTo(headView).with.offset(0);
            make.right.equalTo(headView).with.offset(0);
            make.height.mas_equalTo(@10);
        }];
        
        UIView *newView = [UIView new];
        [headView addSubview:newView];
        [newView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(headView.top).with.offset(10);
            make.left.equalTo(headView).with.offset(0);
            make.right.equalTo(headView).with.offset(0);
            make.bottom.equalTo(headView).with.offset(0);
        }];
        
        UIImageView *leftImageView = [UIImageView new];
        [newView addSubview:leftImageView];
        [leftImageView setImage:[UIImage imageNamed:@"main_left.png"]];
        [leftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(newView.top).with.offset(0);
            make.left.equalTo(newView).with.offset(0);
            make.bottom.equalTo(newView).with.offset(0);
            make.width.mas_equalTo(@2);
        }];
        
        UILabel *leftlable = [UILabel new];
        [newView addSubview:leftlable];
        leftlable.textColor = [UIColor colorWithHexString:@"#03ab9e"];
        leftlable.font = [UIFont systemFontOfSize:16];
        [leftlable setText:@"最新检测结果"];
        [leftlable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(newView.mas_centerY);
            make.left.equalTo(newView).with.offset(15);
            make.bottom.equalTo(newView).with.offset(0);
            make.width.mas_equalTo(@150);
        }];
        return headView;
    }
}

#pragma mark 四个按钮点击
-(void)didSelectDiscountIndex:(NSInteger )index{
    theAppdelegate.tabbarIndex = @"0";
    if (index==0) {
        if (UserModel.password.length>1) {
            ZCRaiseVC *vc = [[ZCRaiseVC alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
            
        }else{
            ZCLoginVC *login = [[ZCLoginVC alloc]init];
            UINavigationController *nalogin = [[UINavigationController alloc]initWithRootViewController:login];
            [self presentViewController:nalogin animated:YES completion:nil];
        }
    }else if (index==1){
        ZCInvolvedVC *involvedVC = [[ZCInvolvedVC alloc]init];
        involvedVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:involvedVC animated:YES];
    }else if (index==2){
        ZCSamplingVC *samVC = [[ZCSamplingVC alloc]init];
        samVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:samVC animated:YES];
        
    }else{
        ZCSeeResultVC *resultVC = [[ZCSeeResultVC alloc]init];
        resultVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:resultVC animated:YES];
    }
}

#pragma mark 分享
-(void)shareButtonPressed:(id *)button{
    CGFloat xWidth = self.view.bounds.size.width - 10.0f;
    CGFloat yHeight = 120.0f;
    UIsharePopoverListView *poplistview = [[UIsharePopoverListView alloc] initWithFrame:CGRectMake(0,0, xWidth/2, yHeight)];
    poplistview.delegate = self;
    poplistview.listView.scrollEnabled = FALSE;
    [poplistview show];
}
- (void)popoverListView:(UIsharePopoverListView *)popoverListView
     didSelectIndexPath:(NSIndexPath *)indexPath{
    
    [NetworkManager  requestGetMyshareWithMid:UserModel.mid password:UserModel.password success:^(NSDictionary *dictResponse) {
        NSLog(@"dict = %@",dictResponse);
        WXMediaMessage *message = [WXMediaMessage message];
         message.title = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"title"]];
        NSLog(@"mesage.title = %@",message.title);
         message.description = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"desc"]];
         NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"imgUrl"]]]];
         message.thumbData = data;

         WXWebpageObject *ext = [WXWebpageObject object];
         ext.webpageUrl = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"link"]];;

         message.mediaObject = ext;
         SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
         req.bText = NO;
         req.message = message;
         if (indexPath.row == 0) {
             req.scene = WXSceneTimeline;
             [WXApi sendReq:req];
         } else if (indexPath.row == 1) {
             req.scene = WXSceneSession;
             [WXApi sendReq:req];
         }

    } failure:^(NSError *error) {
        
    }];
    
}


#pragma mark 监听网络状态

- (void)checkNetworkState
{
     // 1.检测wifi状态
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    
    // 2.检测手机是否能上网络(WIFI\3G\2.5G)
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    
      // 3.判断网络状态
    if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
          NSLog(@"有wifi");
        if (isconn==NO) {
            [self requestAds];
            [self requestMaindata];
            isconn = YES;
        }
     } else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网
           NSLog(@"使用手机自带网络进行上网");
         if (isconn==NO) {
             [self requestAds];
             [self requestMaindata];
             isconn = YES;
         }
           } else { // 没有网络
               isconn = NO;
               NSLog(@"没有网络");
        }
}

@end
